/*
 * @Author: qjb		 
 *  计划任务管理
 * @Date: 2018-08-17 16：35
 */
layui.config({}).use(['element', 'zlConfig', 'zlContext', 'table', 'zltreemenu', 'layer', 'form', 'zlPinYin', 'upload'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		zltreemenu = layui.zltreemenu,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
		zlConfig = layui.zlConfig,
		statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
		dataName = zlConfig.global.result.dataName,
		OK = zlConfig.global.result.okState,
		fullheight = 'full-30',
		customCurr = 1;

	var treeObj,
		isloadsearch = false;
	var treeAction = {
		loadTree: function () {
			treeObj = zltreemenu.render('orgTreeId', {
				dataurl: layui.cache['contentPath'] + '/admin/coreorg/queryorgtreelistbyparentid',
				autoParam: ["RWID"],
				tableId: 'tbUser',
				isMove: false
			}, {
				onClick: function (event, treeId, treeNode) {
					//触发刷新的事件
					customCurr = 1;
					treeAction.raiseResDataEvent(treeNode);
				},
				onAsyncSuccess: function (event, treeId, treeNode, msg) {
					treeObj.selectNode(treeObj.getNodes()[0]);
					treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
				}
			})
		},
		/**发起刷新明细资料的事件 */
		raiseResDataEvent: function (node) {
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, treeAction.getselectnode());
		},
		getselectnode: function () {
			var nodes = treeObj.getSelectedNodes(),
				node = null;
			if (nodes.length > 0) {
				node = nodes[0].RWID;
			} else {
				node = '9C876276D8884BFF94DF343E2A4EED7D';
			}
			return node;
		}
	};
	//加载树
	treeAction.loadTree();

	//渲染用户列表
	var userTb = table.render({
		elem: '#tbUser',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 20,
		limits: [20, 50, 100, 200, 500, 1000],
		page: true,
		updId: "C3DC7918E34347CE97063FD809DA1372",
		toolbar: "#toolbarPlanTask",
		defaultToolbar: ['filter'],
		sortload: true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
				}, {
					type: 'checkbox',
					fixed: 'left'
				}, {
					field: 'OBJNAME',
					title: '名称',
					width: 100,
					sort: true
				}, {
					field: 'OBJCODE',
					title: '编号',
					width: 100,
					sort: true
				}, {
					field: 'CRON',
					title: '执行时间',
					width: 120
				}, {
					field: 'BEANCLASS',
					title: '执行java类',
					width: 170
				}, {
					field: 'PARAMS',
					title: '执行java类的参数',
					width: 170
				}, {
					field: 'SCRIPT',
					title: '执行脚本',
					width: 180
				}, {
					field: 'GROUPNAME',
					title: '备注',
					width: 150
				}, {
					fixed: 'right',
					title: '是否启动',
					width: 100,
					align: 'center',
					templet: function (d) {
						return '<input type="checkbox" name="ENABLE" value="' + d.ENABLE + '" lay-event="ENABLE" lay-skin="switch" lay-text="启动|停止" lay-filter="ENABLE" ' + (d.ENABLE == 1 ? 'checked' : '') + '>';
					}
				}, {
					fixed: 'right',
					width: 180,
					title: '操作',
					align: 'center',
					templet: function (d) {
						if (treeAction.getselectnode() == d.ORGID) {
							return '<a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>' +
								'<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>' +
								'<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
						} else {
							return '<a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>' +
								'<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>'
						}
					}
				}
			]
		]
	});

	var gridAction = {
		frm: [
			'<form class="layui-form " style="margin:8px" id="addnew" >'
			, '   <input type="hidden" name="ORGID">'
			, '   <input type="hidden" name="RWID">'
			, '   <input type="hidden" name="type">'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12 ">'
			, '           <label class="layui-form-label">名称</label>'
			, '           <div class="layui-input-block">'
			, '                 <input type="text" class="layui-input" lay-filter="OBJNAME" name="OBJNAME" maxlength="20" lay-verify="required">'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12 ">'
			, '           <label class="layui-form-label">编号</label>'
			, '           <div class="layui-input-block">'
			, '               <input type="text" class="layui-input" lay-filter="OBJCODE" name="OBJCODE" maxlength="10" lay-verify="required">'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12 ">'
			, '           <label class="layui-form-label">执行时间(cron表达式)</label>'
			, '           <div class="layui-input-block">'
			, '		           <input type="text" class="layui-input" lay-filter="CRON" name="CRON" maxlength="50" lay-verify="required">'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12">'
			, '           <label class="layui-form-label">执行java类名</label>'
			, '           <div class="layui-input-block">'
			, '               <input type="text" class="layui-input" lay-filter="BEANCLASS" name="BEANCLASS" maxlength="100" lay-verify="required">'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12">'
			, '           <label class="layui-form-label">执行java类参数(json格式)</label>'
			, '           <div class="layui-input-block">'
			, '                <textarea class="layui-textarea" lay-filter="PARAMS" maxlength="600" name="PARAMS"></textarea>'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12">'
			, '           <label class="layui-form-label">执行脚本</label>'
			, '           <div class="layui-input-block">'
			, '               <textarea class="layui-textarea" lay-filter="SCRIPT"  name="SCRIPT"></textarea>'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-col-md12">'
			, '           <label class="layui-form-label">是否启动</label>'
			, '           <div class="layui-input-block">'
			, '               <input type="checkbox" name="ENABLE" valueformat="1|0" lay-skin="switch" lay-text="启动|停止">'
			, '           </div>'
			, '       </div>'
			, '   </div>'
			, '   <div class="layui-form-item">'
			, '       <div class="layui-input-block">'
			, '           <button class="layui-btn" lay-submit lay-filter="addnew" >保存</button>'
			, '       </div>'
			, '   </div>'
			, '</form>'
		],
		currentEditObj: undefined,
		fromlayerIndex: undefined,
		search: function () {
			customCurr = 1;
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, treeAction.getselectnode());
		},
		newRow: function () {
			gridAction.fromlayerIndex = layer.open({
				type: 1,
				limit: 999,
				maxmin: true, //最大化按钮
				title: '新增',
				id: 'addPlanLayer',
				area: ['100%', '100%'],
				content: gridAction.frm.join(''),
				success: function (layero, index) {
					$('#addnew input[name=type]').val('add');
					$('#addnew input[name=ORGID]').val(treeAction.getselectnode());
					form.render();
				}
			});
		},
		deleteRows: function (objs, type) {
			if (objs.length == 0) {
				zlContext.warnMsg('请选择需要删除的计划任务');
				return;
			}
			var selorgid = treeAction.getselectnode();
			for (var i = 0; i < objs.length; i++) {
				objs[i].SELORGID = selorgid;
			}
			zlContext.confirm('询问', '是否要删除选择的计划任务?', function (index) {
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/core/plan/delete', JSON.stringify(objs), function (result) {
					if (result[statusName] == OK) {
						if (gridAction.currentEditObj && type == 'single') {
							gridAction.currentEditObj.del();
							gridAction.currentEditObj = undefined;
							var $pageBox = $('#tbUser').siblings('div.layui-table-view').find('span.layui-laypage-count'),
								currCount = $pageBox.html().replace(/[^0-9]/ig, "");
							$pageBox.html('共 ' + --currCount + ' 条');
						} else {
							gridAction.refreshGrid('del', null);
						}
						zlContext.successMsg('删除成功');
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		editRow: function (obj) {
			gridAction.fromlayerIndex = layer.open({
				type: 1,
				limit: 999,
				maxmin: true, //最大化按钮
				title: '编辑',
				id: 'editPlanLayer',
				area: ['100%', '100%'],
				content: gridAction.frm.join(''),
				success: function (layero, index) {
					zlContext.autoFill($('#addnew'), obj);
					$('#addnew input[name=type]').val('edit');
					$('#addnew input[name=ORGID]').val(obj.ORGID);
					$('#addnew input[name=RWID]').val(obj.RWID);
					form.render();
				},
				cancel: function (index, layero) {
					zlContext.isFormDataChange('addnew', gridAction.currentEditObj.data, gridAction, index);
					return false;
				}
			});
		},
		viewRow: function (obj) {
			gridAction.fromlayerIndex = layer.open({
				type: 1,
				limit: 999,
				maxmin: true, //最大化按钮
				title: '查看',
				id: 'checkPlanLayer',
				area: ['100%', '100%'],
				content: gridAction.frm.join(''),
				success: function (layero, index) {
					zlContext.autoFill($('#addnew'), obj);
					$('#addnew input').attr("disabled", "disabled");
					$('#addnew textarea').attr("disabled", "disabled");
					$('#addnew button').addClass("layui-hide");
					$('#addnew input[name=ENABLE]').attr("disabled", "disabled");
					form.render();
				}
			});
		},
		sumbit: function (obj) {
			var editType = $('#addnew input[name=type]').val();
			var param = JSON.stringify(obj);
			if (editType == 'add') {
				zlContext.post(layui.cache['contentPath'] + '/core/plan/add', param, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(gridAction.fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/core/plan/modify', param, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, obj);
						layer.close(gridAction.fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			// if (type == 'edit' && gridAction.currentEditObj) {
			// 	gridAction.currentEditObj.update(row);
			// }
			// else {
			var whereObj = {};
			if (row!=null) {
				whereObj= {'ORGID': row.ORGID}
			}
			var addLoading = layer.load();
			userTb.reload({
				where: whereObj,
				page: {
					curr: customCurr
				},
				done: function (res, curr, count) {
					layer.close(addLoading);
					customCurr = curr;
				}
			});
			// }
			// form.render();
		}
	};

	// $('#btnSeacher').on('click', function () {
	// 	customCurr = 1;
	// 	gridAction.search();
	// });
	$('.zl-container').on('keyup','#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
			customCurr = 1;
		$('.zl-container').attr('data-search',$(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

	//头工具栏事件
	table.on('toolbar(tbUser)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'addPlanTask':
				gridAction.newRow();
				break;
			case 'deletePlanTask':
				var rows = checkStatus.data;
				gridAction.deleteRows(rows,'multi');
				break;
		}
	});
	//监听行工具事件
	table.on('tool(tbUser)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row);
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			var obj = new Array();
			obj.push(row);
			row.del = true;
			gridAction.deleteRows(obj,'single');
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		}
	});
	form.on('switch(ENABLE)', function (obj) {
		var data = table.cache.tbUser;
		var selectIfKey = obj.othis;
		// 获取当前所在行                                                                
		var parentTr = selectIfKey.parents("tr");
		// 获取当前所在行的索引                                                             
		var parentTrIndex = parentTr.attr("data-index");
		if (obj.elem.checked == true) {
			data[parentTrIndex].ENABLE = 1;
		} else {
			data[parentTrIndex].ENABLE = 0;
		}
		zlContext.post(layui.cache['contentPath'] + '/core/plan/modify', JSON.stringify(data[parentTrIndex]), function (result) {
			if (result[statusName] != OK) {
				zlContext.errorMsg(result[msgName]);
			}
		});
	});
	//提交
	form.on('submit(addnew)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
			gridAction.newFields = frm.field;
			return false;
		}
		gridAction.sumbit(frm.field);
		return false;
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (node) {
		var index = layer.msg('数据查询中，请稍候...', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (id, url, param) {
			userTb.reload({
				url: url,
				method: 'get',
				page: {
					curr: customCurr
				},
				where: param,
				done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(index);
					customCurr = curr;
				}
			}, true);
		}
		var params = null;
		var keyvallue = $('#edtSeacherValue').val();
		if (node != null && keyvallue != '') {
			params = {
				ORGID: node,
				KEYVALUE: '%' + keyvallue + '%'
			};
			isloadsearch = true;
		} else if (node == null && keyvallue != '') {
			params = {
				KEYVALUE: '%' + keyvallue + '%'
			};
			isloadsearch = true;
		} else if (node != null && keyvallue == '') {
			params = {
				ORGID: node
			};
		}

		loadGridData('tbUser', layui.cache['contentPath'] + '/core/plan/query', params);
	});
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null);
	
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();

});